package com.xiaoxiao.springbootstudy.controller;

import com.xiaoxiao.springbootstudy.pojo.Item;
import com.xiaoxiao.springbootstudy.pojo.vo.ItemCond;
import com.xiaoxiao.springbootstudy.service.ItemService;
import com.xiaoxiao.springbootstudy.util.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class ItemController {
    @Autowired
    private ItemService itemService;

    @GetMapping("/getCode")
    public String toItemCode() {
        return CodeUtils.toItemCode();
    }

    @PostMapping("/addItem")
    public Map<String, Object> addItem(@RequestBody Item item) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "操作失败.......");
        try {
            item.setStatue(0);
            itemService.save(item);
            result.put("code", 200);
            result.put("msg", "添加商品信息成功.......");
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        return result;

    }

    @PostMapping("/itemList")
    public Map<String, Object> itemList(@RequestBody ItemCond itemCond) {
        return itemService.queryItemListService(itemCond);
    }

    @GetMapping("/downItem/{id}")
    public Map<String, Object> downItem(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "操作失败");
        try {
            Item item = new Item();
            item.setId(id);
            item.setStatue(1);
            itemService.updateById(item);
            result.put("code", 200);
            result.put("msg", "商品下架成功");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    @GetMapping("/deleteItem/{id}")
    public Map<String, Object> deleteItem(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "操作失败");
        try {
            Item item = new Item();
            item.setId(id);
            item.setStatue(2);
            itemService.updateById(item);
            result.put("code", 200);
            result.put("msg", "商品删除成功");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    @PostMapping("/updateItem")
    public Map<String,Object> updateItem(@RequestBody Item item){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败");
        try{
            item.setStatue(0);
            itemService.updateById(item);
            result.put("code",200);
            result.put("msg","更新商品信息成功");
        }catch (Exception ex){
            ex.printStackTrace();
        }


        return result;
    }
}
